#!/usr/bin/python
# -*- coding: utf-8 -*-

#print cherrypy.request.headers
import codecs
import json
import sys
import os
from datetime import *
import time
sys.path.append("./src")
sys.path.append("./merchantKeys")
import psqlWriting
import capchaLib
import tools
from random import shuffle
import threading
from threading import Thread, Lock


mutexL = Lock()
try:
	import cherrypy
except:
	print('Error : Missing cherrypy, we are going to install it now..\n')
	os.system('sudo aptitude install python-cherrypy3')
	import cherrypy


if os.path.exists('documentation/pinp'):
	fin = open('documentation/pinp', 'r')
	key = fin.read().strip()
	fin.close()
else:
	key = getpass.getpass('\n\nPlease enter the password of the database (my data) : ')

hostPort = 5400
curLocation = os.path.split(os.getcwd())[1]
glob_allAnswers = []

try:
	psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'localhost', 'iamar_cards_against_humanity', key)
	hostPort = 44709
except:
	psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'iamar', 'iamar_cards_against_humanity', key)




class deleteUserThread(threading.Thread):
	def __init__(self, key, user_uuid, room_uuid):
		threading.Thread.__init__(self)
		self.key = key
		self.room_uuid = room_uuid
		self.user_uuid = user_uuid


	def run(self):
		try:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'localhost', 'iamar_cards_against_humanity', self.key)
		except:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'iamar', 'iamar_cards_against_humanity', self.key)

		room_users = self.psqlMgr.query("select uuid from users where room_uuid='" + self.room_uuid + "';")
		count = 1

		newUserList = {}
		newUserList['uuid'] = self.room_uuid
		newUserList['whos_turn_id'] = 1
		self.psqlMgr.updateTable('room_info', newUserList)

		for i in room_users:
			if i['uuid'] == self.user_uuid: 
				self.psqlMgr.delete('users', i)
				continue

			newUserList = {}
			newUserList['uuid'] = i['uuid']
			newUserList['user_count_id'] = count
			self.psqlMgr.updateTable('users', newUserList)
			count += 1

		self.psqlMgr.close()





class UpdateAnswerCount(threading.Thread):
	def __init__(self, key, answerUUID, addVal):
		threading.Thread.__init__(self)
		self.key = key
		self.addVal = addVal
		self.answer_uuid = answerUUID


	def run(self):
		try:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'localhost', 'iamar_cards_against_humanity', self.key)
		except:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'iamar', 'iamar_cards_against_humanity', self.key)

		answer = self.psqlMgr.query("select uuid, good_count, bad_count from answers where uuid='" + self.answer_uuid + "';")[0]

		if self.addVal < 0:
			self.addVal = self.addVal*-1
			answer['bad_count'] += self.addVal
			if answer['bad_count'] > 2000000: 
				answer['bad_count'] = 0
				answer['good_count'] = 0
			if answer['bad_count'] > 30 and (answer['bad_count'] > answer['good_count']*2):
				self.psqlMgr.delete('answers',answer)
			else:
				self.psqlMgr.updateTable('answers',answer)
		else:
			answer['good_count'] += self.addVal
			if answer['good_count'] > 2000000: 
				answer['bad_count'] = 0
				answer['good_count'] = 0

			self.psqlMgr.updateTable('answers',answer)

		self.psqlMgr.close()




class updateAlreadyUsed(threading.Thread):
	def __init__(self, key, data):
		threading.Thread.__init__(self)
		self.key = key
		self.data = data


	def run(self):
		try:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'localhost', 'iamar_cards_against_humanity', self.key)
		except:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'iamar', 'iamar_cards_against_humanity', self.key)

		for i in self.data:
			self.psqlMgr.updateTable('questions_already_used', i)
		self.psqlMgr.close()




class updateDB(threading.Thread):
	def __init__(self, key):
		threading.Thread.__init__(self)
		try:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'localhost', 'iamar_cards_against_humanity', key)
		except:
			self.psqlMgr = psqlWriting.psqlManager('iamar_cards_against_humanity', 'iamar', 'iamar_cards_against_humanity', key)


	def run(self):
		global glob_allAnswers

		while True:
			try:
				mutexL.acquire()
				glob_allAnswers = self.psqlMgr.query("select * from answers;")

				allRooms = self.psqlMgr.query("select uuid, time_of_creation from room_info;")
				for room in allRooms:
					timeSinceLast = datetime.utcnow() - tools.stringToUTCTime( room['time_of_creation'] )
					print 'Time since last :' , timeSinceLast.seconds
					if timeSinceLast.seconds > 60*60*10:
						roomUsers = self.psqlMgr.query("select uuid from users where room_uuid='" + room['uuid'] + "';")
						for user in roomUsers:
							self.psqlMgr.delete('users',user)

						qAU = self.psqlMgr.query("select uuid from questions_already_used where room_uuid='" + room['uuid'] + "';")
						for item in qAU:
							self.psqlMgr.delete('questions_already_used',item)

						self.psqlMgr.delete('room_info',room)


			except Exception, e:
				print str(e)

			finally:
				mutexL.release()
				time.sleep(1000*60*20)




t = updateDB(key)
t.setDaemon(True)
t.start()


#Flying sex snakes d1db3b0009be8aa7ba6f8cb25afdfbfa 
#allA = psqlMgr.query("select * from answers where uuid='d1db3b0009be8aa7ba6f8cb25afdfbfa'")
#allA = psqlMgr.query("select * from answers where bad_count<>0 or good_count<>0;")
#for i in allA:
#	print i

##-----------
allA = psqlMgr.query('select * from questions_already_used')
for i in allA:
	psqlMgr.delete('questions_already_used', i)

allA = psqlMgr.query('select * from users')
for i in allA:
	i['my_answers'] = ''
	psqlMgr.updateTable('users', i)
##------


print 'using port = ' , hostPort , ' location = ' , curLocation , ' \n\n'


class cardsA(object):
	ImgCodeError = 'Sorry, but the image code you provided is wrong. You can refresh and try a different image if this is too hard.'
	def index(self):
		script = '<script type="text/javascript" src="jscript/index.js"></script>'
		script += '<script type="text/javascript" src="jscript/ajaxCalls.js"></script>'
		script += '<script type="text/javascript" src="jscript/languages.js"></script>'
		script += '<script type="text/javascript" src="jscript/tools.js"></script>'
		script += '<script type="text/javascript" src="jscript/createObjects.js"></script>'
		script += '<script type="text/javascript" src="jscript/json2.js"></script>'

		html = self.outHtml('html/index.html')
		html = html.replace('<!-- scripts -->',script)
		return html
			

	def submitNewQuestion(self, NewAnswer, capchaFileName, capchaKey , language, fuckIE):
		try:
			if not capchaLib.checkKeyWithFile(capchaFileName, capchaKey):
				return cardsA.ImgCodeError
			
			NewAnswer = unicode(NewAnswer).encode("utf-8")
			answerInfo = psqlMgr.query("select * from questions where question='" + NewAnswer + "';")
			if( len(answerInfo) != 0 ): return 'This question already exists try another one'
	
			newEntry = {}
			newEntry['uuid'] = psqlMgr.uuid()
			newEntry['question'] = NewAnswer
			newEntry['good_count'] = 0
			newEntry['bad_count'] = 0
			newEntry['language'] = language
	
			psqlMgr.insertTable('questions', newEntry)
			return 'ok'
		except Exception, e:
			return str(e)

	def submitNewAnswer(self, NewAnswer, capchaFileName, capchaKey , language, fuckIE):
		try:
			if not capchaLib.checkKeyWithFile(capchaFileName, capchaKey):
				return cardsA.ImgCodeError

			NewAnswer = unicode(NewAnswer).encode("utf-8")
	
			answerInfo = psqlMgr.query("select * from answers where answer='" + NewAnswer + "';")
			if( len(answerInfo) != 0 ): return 'This answer already exists try another one'
	
			newEntry = {}
			newEntry['uuid'] = psqlMgr.uuid()
			newEntry['answer'] = NewAnswer
			newEntry['good_count'] = 0
			newEntry['bad_count'] = 0
			newEntry['language'] = language
	
			psqlMgr.insertTable('answers', newEntry)
			return 'ok'
		except Exception, e:
			return str(e)

	def getNewCapchaName(self, capcha, fuckIE):
		try:
			now = datetime.now()
	
			for i in os.listdir('./capImg'):
				timeCreation = datetime.fromtimestamp(os.path.getmtime('./capImg/' + i))
				aliveTime = (now - timeCreation).seconds
				
				if(aliveTime > 600): #greater than an hour
					if os.path.splitext(i)[1] == '.jpg':
						os.remove('./capImg/' + i)
	
			if os.path.exists(capcha):
				os.remove(capcha)
	
			a = capchaLib.gen_captcha('fonts/', 'capImg/', 38)
			return a
		except Exception, e:
			print(str(e))
			return 'error'



	def outHtml(self,path):
		fin = open(path, 'r')
		a = fin.read()
		fin.close()
		return a

	def createNewRoom(self, newRoomName, roomPassword, capchaFileName, capchaKey, language, fuckIE):
		if not capchaLib.checkKeyWithFile(capchaFileName, capchaKey):
			return cardsA.ImgCodeError

		newRoomName = unicode(newRoomName).encode("utf-8")
		answerInfo = psqlMgr.query("select * from room_info where room_name='" + newRoomName + "';")
		if( len(answerInfo) != 0 ): return 'This room name already exists, try another one'

		utc_datetime = datetime.utcnow()
		updateLast = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")

		newRoom = {}
		newRoom['uuid'] = psqlMgr.uuid()
		newRoom['room_name'] = newRoomName
		newRoom['whos_turn_id'] = 1
		newRoom['time_of_creation'] = updateLast
		newRoom['room_password'] = roomPassword
		newRoom['language'] = language

		psqlMgr.insertTable('room_info', newRoom)
		return 'ok'

	def startGame(self, room_uuid, player_uuid):
		roomExist = psqlMgr.query("select * from room_info where uuid='" + room_uuid + "';")

		script = '<script type="text/javascript" src="jscript/game.js"></script>'
		script += '<script type="text/javascript" src="jscript/ajaxCalls.js"></script>'
		script += '<script type="text/javascript" src="jscript/tools.js"></script>'
		script += '<script type="text/javascript" src="jscript/createObjects.js"></script>'
		script += '<script type="text/javascript" src="jscript/json2.js"></script>'

		html = self.outHtml('html/index.html')
		html = html.replace('<!-- scripts -->',script)

		userExist = psqlMgr.query("select uuid from users where uuid='" + player_uuid + "';")
		if len(userExist) == 0: 
			html = html.replace('<div id=contentID style="text-align:center;width:100%;"> </div>','<br><br>You have been deleted, please try to re-login at yumbery.com')
		elif len(roomExist) == 0: 
			html = html.replace('<div id=contentID style="text-align:center;width:100%;"> </div>','<br><br>This room does not exist')

		return html

	def enterRoom(self, newRoomName, roomPassword, userId, fuckIE):
		newRoomName = unicode(newRoomName).encode("utf-8")
		answerInfo = psqlMgr.query("select * from room_info where room_name='" + newRoomName + "' and room_password='" + roomPassword + "';")
		if( len(answerInfo) == 0 ): 
			retVal = {'result':'error', 'msg':'This room and password does not match anything.'}
			return json.dumps(retVal)

		answerInfo = answerInfo[0]

		users = psqlMgr.query("select uuid, user_name from users where room_uuid='" + answerInfo['uuid'] + "';")
		for i in users:
			if i['user_name'] == userId:
				retVal = {'result':'ok', 'room':answerInfo['uuid'], 'player': i['uuid']}
				return json.dumps(retVal)

		newUser = {}
		newUser['uuid'] = psqlMgr.uuid()
		newUser['user_name'] = userId
		newUser['room_uuid'] = answerInfo['uuid']
		newUser['user_count_id'] = len(users) + 1
		newUser['question_ids'] = ''
		newUser['points'] = 0
		newUser['my_choice_answer'] = '' 

		psqlMgr.insertTable('users', newUser)
		retVal = {'result':'ok', 'room':answerInfo['uuid'], 'player': newUser['uuid']}
		return json.dumps(retVal)

	def getAllPalyers(self, room_uuid, fuckIE):
		allUsers = psqlMgr.query("select user_name, points from users where room_uuid='" + room_uuid + "';")
		return json.dumps(allUsers)


	def getOneNewAnswer(self, room_uuid):
		answers = psqlMgr.query("select answer,uuid from answers;")

		x = [i for i in range(len(answers))]
		shuffle(x)

		viewAnswers = psqlMgr.query("select answer_uuid from questions_already_used where room_uuid='" + room_uuid + "';")
		alreadyAnswers = []
		for i in viewAnswers:
			alreadyAnswers.append( i['answer_uuid'] )

		userAnswers = []
		for i in x:
			if answers[i]['uuid'] not in alreadyAnswers:
				return [answers[i]['uuid'], answers[i]['answer']]
		return ['','']

	def getNewAnswer(self, room_uuid, player_uuid, language):
		global glob_allAnswers

		try:
			mutexL.acquire()
	
			x = [i for i in range(len(glob_allAnswers))]
			shuffle(x)
	
			viewAnswers = psqlMgr.query("select answer_uuid from questions_already_used where room_uuid='" + room_uuid + "';")
			alreadyAnswers = []
			for i in viewAnswers:
				alreadyAnswers.append( i['answer_uuid'] )
	
			userAnswers = {}
			answersTOInsert = []
			for i in x:
				if glob_allAnswers[i]['uuid'] not in alreadyAnswers:
					if glob_allAnswers[i]['language'] != language: continue

					userAnswers[glob_allAnswers[i]['uuid']] = glob_allAnswers[i]['answer']
					updateQ = {}
					updateQ['uuid'] = psqlMgr.uuid()
					updateQ['room_uuid'] = room_uuid
					updateQ['answer_uuid'] = glob_allAnswers[i]['uuid']
					answersTOInsert.append(updateQ)
	
	
					if len(userAnswers.keys()) > 9:
						updateQ = {}
						updateQ['uuid'] = player_uuid
						updateQ['my_answers'] = json.dumps(userAnswers)
						updateQ['delete_counter'] = 0
						psqlMgr.updateTable('users', updateQ)
						
						t = updateAlreadyUsed(key, answersTOInsert)
						t.setDaemon(True)
						t.start()

						return json.dumps(userAnswers)
	
			updateQ = {}
			updateQ['uuid'] = player_uuid
			updateQ['my_answers'] = json.dumps(userAnswers)
			updateQ['delete_counter'] = 0
			psqlMgr.updateTable('users', updateQ)

			return json.dumps(userAnswers)
		finally:
			mutexL.release()


	def getNewQuestion(self, room_uuid, language):
		questions = psqlMgr.query("select question,uuid from questions where language='" + language + "';")

		x = [i for i in range(len(questions))]
		shuffle(x)

		viewQuestions = psqlMgr.query("select question_uuid from questions_already_used where room_uuid='" + room_uuid + "';")
		alreadyQuestion = []
		for i in viewQuestions:
			alreadyQuestion.append( i['question_uuid'] )

		for i in x:
			if questions[i]['uuid'] not in alreadyQuestion:

				updateQ = {}
				updateQ['uuid'] = psqlMgr.uuid()
				updateQ['room_uuid'] = room_uuid
				updateQ['question_uuid'] = questions[i]['uuid']
				psqlMgr.updateTable('questions_already_used', updateQ)

				return [questions[i]['question'], questions[i]['uuid']]

		return False

	def nextRound(self, room_uuid, player_uuid, question, fuckIE):
		roomInfo = psqlMgr.query("select * from room_info where uuid='" + room_uuid + "';")
		if len(roomInfo) == 0:
			retVal = {'result':'error', 'error':'This room no longer exists'}
			return json.dumps(retVal)
		roomInfo = roomInfo[0]

		if tools.SafeStringToSpecial(question) == tools.SafeStringToSpecial(roomInfo['current_question']):
			if roomInfo['current_question'] != '':
				retVal = {'result':'error', 'error':'This round has not ended yet'}
				return json.dumps(retVal)

		userInfo = psqlMgr.query("select * from users where uuid='" + player_uuid + "';")
		if len(userInfo) == 0:
			retVal = {'result':'error', 'error':'This user has been deleted, please re-login'}
			return json.dumps(retVal)
		userInfo = userInfo[0]

		if roomInfo['whos_turn_id'] == userInfo['user_count_id']:
			qInfo = self.getNewQuestion(room_uuid, roomInfo['language'])
			if qInfo == False:
				retVal = {'result':'error', 'error':'This room no longer exists'}
				return json.dumps(retVal)

			retVal = {'result':'giveQuestion', 'question': qInfo[0], 'uuid':qInfo[1]}
			return json.dumps(retVal)
		else:
			if userInfo['my_answers'] == '':
				retVal = {'result':'giveAnswer', 'answers': self.getNewAnswer(room_uuid, player_uuid, roomInfo['language'])}
			else:
				retVal = {'result':'giveAnswer', 'answers': userInfo['my_answers']}

			return json.dumps(retVal)


		return json.dumps(retVal)

	def skipQuestion(self, room_uuid, player_uuid, question_uuid, fuckIE):
		try:
			roomInfo = psqlMgr.query("select * from room_info where uuid='" + room_uuid + "';")[0]
			questionInfo = psqlMgr.query("select * from questions where uuid='" + question_uuid + "';")[0]
	
			questionInfo['bad_count'] = questionInfo['bad_count'] + 1
			psqlMgr.updateTable('questions', questionInfo)
			if questionInfo['bad_count'] > 30:
				if (questionInfo['bad_count']/questionInfo['good_count']) > 1:
					psqlMgr.delete('questions', questionInfo)
	
			userInfo = psqlMgr.query("select * from users where uuid='" + player_uuid + "';")
			if len(userInfo) == 0:
				retVal = {'result':'error', 'error': "This user has been deleted"}
				return json.dumps(retVal)
			userInfo = userInfo[0]
	
			qInfo = self.getNewQuestion(room_uuid, roomInfo['language'])
			retVal = {'result':'giveQuestion', 'question': qInfo[0], 'uuid': qInfo[1]}
			return json.dumps(retVal)
		except Exception, e:
			retVal = {'result':'error', 'erro': str(e)}
			return json.dumps(retVal)


	def getPlayerCards(self, room_uuid, player_uuid, fuckIE):
		roomInfo = psqlMgr.query("select * from room_info where uuid='" + room_uuid + "';")
		if len(roomInfo) == 0:
			retVal = {'result':'error', 'error':'This room no longer exists'}
			return json.dumps(retVal)
		roomInfo = roomInfo[0]
		if roomInfo['whos_turn_id'] == 0:
			roomInfo['whos_turn_id'] = 1
			updateRoom = {}
			updateRoom['uuid'] = room_uuid
			updateRoom['whos_turn_id'] = 1
			psqlMgr.updateTable('room_info', updateRoom)

		userInfo = psqlMgr.query("select * from users where uuid='" + player_uuid + "';")[0]
		
		if roomInfo['whos_turn_id'] == userInfo['user_count_id']:
			qInfo = self.getNewQuestion(room_uuid, roomInfo['language'])
			retVal = {'result':'giveQuestion', 'question': qInfo[0], 'uuid': qInfo[1]}
			return json.dumps(retVal)
		else:
			if userInfo['my_answers'] == '':
				retVal = {'result':'giveAnswer', 'answers': self.getNewAnswer(room_uuid, player_uuid, roomInfo['language'])}
			else:
				retVal = {'result':'giveAnswer', 'answers': userInfo['my_answers']}

			return json.dumps(retVal)

	def getRoomQuestion(self, room_uuid, user_uuid, fuckIE):
		roomInfo = psqlMgr.query("select whos_turn_id, current_question from room_info where uuid='" + room_uuid + "';")
		if len(roomInfo) == 0:
			retVal = {'result':'error', 'error': 'This room does not exist'}
			return json.dumps(retVal)

		user = psqlMgr.query("select uuid, user_count_id from users where uuid='" + user_uuid + "';")
		if len(user) == 0:
			retVal = {'result':'error', 'error': 'This user does not exist'}
			return json.dumps(retVal)
		user = user[0]
		roomInfo = roomInfo[0]

		if user['user_count_id'] == roomInfo['whos_turn_id']:
			retVal = {'result':'is questioner'}
			return json.dumps(retVal)


		if roomInfo['current_question'] == "":
			c = "select uuid, user_name from users where room_uuid='" +room_uuid
			c += "' and user_count_id=" + str(roomInfo['whos_turn_id']) + ";"
			userInfo = psqlMgr.query(c)[0]
			
			retVal = {'result':'not yet', 'msg': userInfo}
			return json.dumps(retVal)
		else:
			retVal = {'result':'ok', 'question': roomInfo['current_question']}
			return json.dumps(retVal)

	def onSelectQuestion(self,room_uuid, user_uuid, questionChosen, question_uuid, fuckIE):
		user = psqlMgr.query("select uuid from users where uuid='" + user_uuid + "';")
		if len(user) == 0:
			retVal = {'result': 'error', 'error': 'This user has been deleted.'}
			return json.dumps(retVal)

		questionChosen = unicode(questionChosen).encode("utf-8")
		updateQuestion = {'uuid': room_uuid, 'current_question': questionChosen}
		psqlMgr.updateTable('room_info', updateQuestion)

		questionInf = psqlMgr.query("select * from questions where uuid='" + question_uuid + "';")[0]
		questionInf['good_count'] = questionInf['good_count'] + 1
		psqlMgr.updateTable('questions', questionInf)

		retVal = {'result': 'ok', 'current_question': questionChosen}
		return json.dumps(retVal)

	
	def removeAnswer(self, user_uuid, room_uuid, selectedAnswer, answer_uuid, fuckIE):
		user = psqlMgr.query("select uuid, my_answers from users where uuid='" + user_uuid + "';")[0]
	
		userAnswers = json.loads(user['my_answers'])
		del userAnswers[answer_uuid]

		newAns = self.getOneNewAnswer(room_uuid)
		userAnswers[newAns[0]] = newAns[1]

		user['my_answers'] = json.dumps(userAnswers)
		user['delete_counter'] = 0
		psqlMgr.updateTable('users', user)

		t = UpdateAnswerCount(key, answer_uuid, -1)
		t.setDaemon(True)
		t.start()

		retVal = {'result': 'cardRemoved'}
		return json.dumps(retVal)


	def submitAnswerChosen(self, user_uuid, room_uuid, selectedAnswer, answer_uuid, fuckIE):
		cmd = "select uuid, user_name, user_count_id, points, my_choice_answer from users where room_uuid='" + room_uuid + "';"
		users = psqlMgr.query(cmd)
		userCount = []
		winnerName = 'A randomly chosen card'
		for i in users:
			userCount.append(i['user_count_id'])
			if i['my_choice_answer'] == selectedAnswer:
				i['points'] = i['points'] + 1
				winnerName = i['user_name']

			i['my_choice_answer'] = ''
			i['delete_counter'] = 0
			psqlMgr.updateTable('users',i)
		
		cmd = "select uuid, whos_turn_id from room_info where uuid='" + room_uuid + "';"
		roomInfo = psqlMgr.query(cmd)[0]
		roomInfo['whos_turn_id'] = roomInfo['whos_turn_id'] + 1
		roomInfo['current_question'] = ''
	
		if roomInfo['whos_turn_id'] not in userCount:
			roomInfo['whos_turn_id'] = 1
		psqlMgr.updateTable('room_info', roomInfo)

		retVal = {'result': 'userWon', 'msg': winnerName + ' has won.'}
		return json.dumps(retVal)


	def submitAnswer(self, user_uuid, room_uuid, selectedAnswer, answer_uuid, fuckIE):
		user = psqlMgr.query("select uuid, my_answers from users where uuid='" + user_uuid + "';")
		if len(user) == 0:
			retVal = {'result':'error', 'error': 'This user has been deleted'}
			return json.dumps(retVal)

		user = user[0]
		t = UpdateAnswerCount(key, answer_uuid, 10)
		t.setDaemon(True)
		t.start()

		userAnswers = json.loads(user['my_answers'])
		del userAnswers[answer_uuid]

		newAns = self.getOneNewAnswer(room_uuid)
		userAnswers[newAns[0]] = newAns[1]

		updateAns = {}
		updateAns['uuid'] = user_uuid
		updateAns['my_choice_answer'] = selectedAnswer
		updateAns['my_answers'] = json.dumps(userAnswers)
		psqlMgr.updateTable('users', updateAns)

		retVal = {'result': 'ok'}
		return json.dumps(retVal)

	def getEverybodysAnswer(self, room_uuid, fuckIE):
		answers = psqlMgr.query("select my_choice_answer from users where room_uuid='" + room_uuid + "' and my_choice_answer<>'';")
		if len(answers) == 0:
			retVal = {'result':'error', 'error': 'Nobody has summited an answer yet'}
			return json.dumps(retVal)

		randomCard = self.getOneNewAnswer(room_uuid)
		AllAnswers = ''
		for i in answers:
			AllAnswers += i['my_choice_answer'] + '|next-Answer|'

		AllAnswers += randomCard[1]

		retVal = {'result':'ok', 'answers': AllAnswers}
		return json.dumps(retVal)

	def deleteUser(self, user_uuid, room_uuid, fuckIE):
		userI = psqlMgr.query("select delete_counter from users where uuid='" + user_uuid + "';")
		if len(userI) == 0:
			retVal = {'result':'ok', 'msg': 'This user has been deleted'}
			return json.dumps(retVal)

		userI = userI[0]
		userI['uuid'] = user_uuid

		if userI['delete_counter'] == 1:
			t = deleteUserThread(key, user_uuid, room_uuid)
			t.setDaemon(True)
			t.start()

			retVal = {'result':'ok', 'msg': 'This user has been deleted'}
			return json.dumps(retVal)

		userI['delete_counter'] = 1
		userI = psqlMgr.updateTable('users', userI)
		retVal = {'result':'ok', 'msg': 'This user needs one more vote to delete'}
		return json.dumps(retVal)

	#new function
	deleteUser.exposed = True
	removeAnswer.exposed = True
	skipQuestion.exposed = True
	nextRound.exposed = True
	submitAnswerChosen.exposed = True
	getEverybodysAnswer.exposed = True
	submitAnswer.exposed = True
	onSelectQuestion.exposed = True
	getRoomQuestion.exposed = True
	getPlayerCards.exposed = True
	getAllPalyers.exposed = True
	startGame.exposed = True
	enterRoom.exposed = True
	createNewRoom.exposed = True
	submitNewQuestion.exposed = True
	submitNewAnswer.exposed = True
	getNewCapchaName.exposed = True
	index.exposed = True


if __name__ == '__main__':
	current_dir = os.path.dirname(os.path.abspath(__file__))
				 
	
	conf = 	{
				'/': {'tools.encode.on':True, 'tools.encode.encoding':'utf-8', 'tools.proxy.on':True},
				'/': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, '')},
				'/html': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'html'), 'tools.staticdir.content_types': {'css': 'text/css', 'manifest': 'text/cache-manifest'}},
				'/img': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'img')},
				'/jscript': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'jscript')},
				'/capImg': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'capImg')},
				 'global':	{ 'server.environment': 'production',
				'engine.autoreload_on': True,
				'engine.autoreload_frequency': 5,
				'server.socket_host': '0.0.0.0',
				'server.socket_port': hostPort}
			}
	
	
	cherrypy.quickstart(cardsA(), '/', config=conf)

	



